package controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import entity.Users;
import entity.Video;
import entity.VideoList;
import service.UsersService;
import service.VideoListService;
import service.VideoService;

@Controller
@RequestMapping("/users")
public class UsersController {

	@Autowired
	UsersService userService;
	@Autowired
	VideoService videoService;
	@Autowired
	VideoListService videoListService;
	@Autowired
	Users users_msg;

	// 登录
	@RequestMapping("/login")
	public void login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
		try {
			if (userService.find(username, password) == false) { // 是否存在此账户
				response.getWriter().write("error");
			} else {
				loginOK(username, request);
				response.getWriter().write("success");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void loginOK(String username, HttpServletRequest request) {
		Users user = userService.findByUserName(username);
		request.getSession().setAttribute("loginuser", user);   //保存于session中
		request.getSession().setAttribute("username", username);//接受一个username，然后保存到session里面
	}

	// 注册
	@RequestMapping(value = "/add")
	public void add(String username, String password, HttpServletRequest request, HttpServletResponse response) {
		try {
			if (userService.add(username, password) == false) {
				response.getWriter().write("error");
			} else {
				response.getWriter().write("success");
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	//根据用户账号查找账号信息、上传的视频、创建的播单
	@RequestMapping("/findByUserName")
	public String findByUserName(String username, Model model) {
		Users users = userService.findByUserName(username);
		model.addAttribute("user", users);

		List<Video> videoList = videoService.findVideoByUserId(users.getId());
		model.addAttribute("videoList", videoList);

		List<VideoList> list = videoListService.findListByUserId(users.getId());
		model.addAttribute("list", list);

		return "/page/my_space";
	}

	@RequestMapping("/findByUserName1")
	public String findByUserName1(String username, Model model) {
		Users users = userService.findByUserName(username);
		model.addAttribute("user", users);

		return "/page/user_space";
	}

	// 更新个人资料
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update_base(String username, Model model) {// 更新的时候需要先获取到一个user对象
		Users user = userService.findByUserName(username);// 调用底层获得user对象的方法
		String[] msg = user.getAddress().split("#");// 获取到user对象里面的地址值，因为存入的是“省份#城市”的格式，所以现在将他们分离出来
		String pv = msg[0];// 将user对象获取到的地址值中的省份赋值到pv里
		String cv = msg[1];// 将user对象获取到的地址值中的城市赋值到cv里
		
		//获取个人的播单信息
		List<VideoList> list = videoListService.findListByUserId(user.getId());
		
		model.addAttribute("list", list);
		model.addAttribute("pv", pv);// 把从user对象里获取到的数据返回给前端页面
		model.addAttribute("cv", cv);// 把从user对象里获取到的数据返回给前端页面
		model.addAttribute("users", user);//// 把从user对象返回给前端页面
		
		System.out.println(pv);// 测试输出
		System.out.println(cv);// 测试输出
		System.out.println(user.getBirthday());// 测试输出
		return "/page/user_space";// 返回JSP页面的名称
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update_base(String username, String province1, String city, String birthday, String intro, String nickname,
			HttpServletRequest request, HttpServletResponse response, Model model) {

		System.out.println(username);

		String pv = province1;// pv表示从前端的province1里面获取到的省份属性值
		String cv = city;// cv表示从前端的city里面获取到的城市属性值
		String pcv = province1 + "#" + city;// 因为前端页面需要分开省份跟城市，所以存入数据库的时候需要讲省份和城市的属性值分开，用#代表
		String bir = birthday;// bir表示从前端页面的birthday获取到的出生属性值
		String in = intro;// in表示从前端页面intro里获取到的个人简介属性值

		userService.updateaddress(pcv, username);// 底层的方法去执行更新
		userService.updatebirthday(bir, username);// 底层的方法去执行更新
		userService.updateintro(intro, username);// 底层的方法去执行更新
		userService.updateNickname(nickname, username);
		Users user = userService.findByUserName(username);// 重新利用底层的方法去读书更新后数据库的数据
		
		//修改个人信息后，修改登陆信息
		request.getSession().removeAttribute("username");
		request.getSession().removeAttribute("loginuser");
		request.getSession().setAttribute("loginuser", user);   //保存于session中
		request.getSession().setAttribute("username", user.getUsername());//接受一个username，然后保存到session里面
		
		model.addAttribute("users", user);// 再次把更新后获取到的user对象返回到前端里

		String[] msg = user.getAddress().split("#");// 把更新后的数据再重新获取一次返回到前端页面中
		
		model.addAttribute("pv", pv);// 把更新后的数据再重新获取一次返回到前端页面中
		model.addAttribute("cv", cv);// 把更新后的数据再重新获取一次返回到前端页面中

		return "/page/user_space";

	}
	
	
	//更改密码
	@RequestMapping(value = "/updatepassword", method = RequestMethod.POST)
	public void update_password(String username, String old_password, String new_password, String confirm_password,
			HttpServletRequest request, HttpServletResponse response) {

		
		Users user = userService.findByUserName(username);//先获得user对象
		String s = user.getPassword();//获取user对象中的密码数据
		String a = old_password;//获取前端返回过来的密码
		
		try {
			if(s.equals(a)) {//开始判断前端输入的原始密码跟数据库的密码是否一致
				System.out.println("成功执行第一层IF");
				if (new_password.equals(confirm_password)) {
					System.out.println("成功执行第二层IF");
					userService.updatepassword(new_password,username);
					response.getWriter().write("success1");
					System.out.println("更新成功");
				} else {
					response.getWriter().write("error2");
				}
			} else {
				response.getWriter().write("error3");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	
	
	@RequestMapping("/uploadheadicon")
	public String upload(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<String> filenames = new ArrayList<>();
		Date date = new Date();
		String username = (String) request.getSession().getAttribute("username");//获取当前登陆用户的账号
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		
		
		if(multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator files = multipartRequest.getFileNames();
		
			
			while(files.hasNext()) {
				MultipartFile file = multipartRequest.getFile(files.next().toString());
				System.out.println("获取文件名字:"+file.getOriginalFilename());
				String originalFilename = file.getOriginalFilename();
				// 截取文件名字：---a.jpg
				String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//获取文件名.的后缀名
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
				String s=sdf.format(date);
				String lastname=s + "-" + username+"."+substring;
				
				System.out.println("打印最后修改的名字"+lastname);
				
				userService.uploadheadicon(lastname, username);
				
				if(!file.getContentType().startsWith("image")) {
					continue;
				}
				if(!file.getOriginalFilename().equals("")) {
					String path = request.getSession().
									getServletContext().
									getRealPath("/upload/head-icon") + "\\" + lastname;
					String path_base = path.substring(path.indexOf("upload"));//这个path_bass就是存在数据库里面的picUrl
					
					try {
						file.transferTo(new File(path));
						filenames.add(username + "-"+ file.getOriginalFilename());
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
					
				}
			}
		}
		
		Users user = userService.findByUserName(username);// 重新利用底层的方法去读书更新后数据库的数据
		String[] msg = user.getAddress().split("#");// 把更新后的数据再重新获取一次返回到前端页面中
		String pv = msg[0];
		String cv = msg[1];
		
		
		model.addAttribute("users", user);// 再次把更新后获取到的user对象返回到前端里
		model.addAttribute("pv", pv);// 把更新后的数据再重新获取一次返回到前端页面中
		model.addAttribute("cv", cv);// 把更新后的数据再重新获取一次返回到前端页面中
		
		request.setAttribute("filenames", filenames);  
		return "/page/user_space";
	}

	
	public String makeStorePath(String storePath, String username) {
		
		String path=storePath + "\\" + username;
		// 假如这个文件夹不存在，就创建一个文件夹
		File file=new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		return path;
	}
	
	
	private Date formatTime(String birthday) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date parse = null;
		try {
			parse = sdf.parse(birthday);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return parse;
	}

	@RequestMapping(value = "/outuser")
	public String outuser(HttpServletRequest request, HttpServletResponse response) {
			request.getSession().removeAttribute("username");
			request.getSession().removeAttribute("loginuser");
		return "redirect:/video/findByNumberAndTime?categoryId=1&isCharge=1&categoryId2=3";
	}
}
